package cn.j229.bug.zhongxuan.service.impl;

import cn.j229.bug.zhongxuan.mapper.SysUserMapper;
import cn.j229.bug.zhongxuan.pojo.SysUser;
import cn.j229.bug.zhongxuan.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

    // 调用mapper执行dao层的持久化操作

    // 关于自动装配的方式有三种：
    // 第一种：字段上装配并实现注入
    @Resource
    SysUserMapper sysUserMapper = null;

//    // 第二种：在setter上装配并实现注入
//    public void setSysUserMapper(SysUserMapper sysUserMapper){
//        this.sysUserMapper = sysUserMapper;
//    }
//
//    // 第三种：在构造方法上装配并实现注入(但，构造方法上装配只能用@Autowire，不能用@Resource)
//    @Autowired
//    public SysUserServiceImpl(SysUserMapper sysUserMapper){
//        this.sysUserMapper = sysUserMapper;
//    }

    public Boolean login(String jobNumber, String password) {
        // 数据校验

        // 加密加盐

        // 执行DAO层(Mapper)
       /* SqlSessionFactoryBuilder builder = null;
        SqlSessionFactory build = builder.build(null);
        SqlSession sqlSession = build.openSession();
        SysUserMapper mapper = sqlSession.getMapper(SysUserMapper.class);
        Boolean isSuccessed =  mapper.findByJobNumberAndPwd(jobNumber,password);
        return isSuccessed;*/

        SysUser sysUser = sysUserMapper.findByJobNumberAndPassword(jobNumber, password);
        return sysUser!=null?true:false;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.SUPPORTS,rollbackFor = {Throwable.class})
    public List<Map<String, Object>> findById2(Integer id) {
        return sysUserMapper.findById2(id);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,rollbackFor = {Throwable.class})
    public boolean register(SysUser sysUser) {
        SysUser byId = sysUserMapper.findById(sysUser.getId());
        if(byId == null){
            Integer save = sysUserMapper.save(sysUser);
            if(save > 0){
                return true;
            }
            return false;
        }
        return false;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.SUPPORTS,rollbackFor = {Throwable.class})
    public SysUser findById(Integer id) {
        return sysUserMapper.findById(id);
    }

}
